package com.ruoyi.system.service.impl;

import cn.hutool.core.io.FileUtil;
import com.ruoyi.system.service.UploadService;
import jakarta.servlet.http.HttpServletRequest;
import org.apache.commons.io.FilenameUtils;
import org.apache.commons.lang3.RandomStringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

@Service
public class UploadServiceImpl implements UploadService {

    //获取配置文件中上传到本地的文件路径,通过nginx访问
    @Value("${resourcefile:resourcefile}")
    private String resourcefile="resourcefile";

    @Value("${IPAddress:http://localhost:8888}")
    private String IPAddress ="http://localhost:8888";

    @Value("${pathprefix:uploadFile}")
    private String pathprefix;

    @Override
    public String uploadToLocal(MultipartFile file) throws IOException {
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.currentRequestAttributes();
        HttpServletRequest request = attributes.getRequest();

        String host = request.getHeader("Host");
        int port = request.getServerPort();
        String scheme = request.getScheme();
        String contextPath = request.getContextPath();
        String pathInfo = request.getPathInfo();
        String requestURI = request.getRequestURI();
        System.out.println(host+",port:"+port+",scheme:"+scheme);
        System.out.println(contextPath);
        System.out.println(pathInfo);
        System.out.println(requestURI);
//        if(host.contains("localhost")||host.contains("127.0.0.1")||host.contains("192.168.")){
//        }else{
//        }
        IPAddress =scheme+"://"+host;
        // 文件后缀
        String fileExtension = FilenameUtils.getExtension(file.getOriginalFilename());
        // 这里可自定义文件名称，比如按照业务类型/文件格式/日期
        String dateString = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyyMMddHHmmssS")) + RandomStringUtils.randomNumeric(2);
        String fileName = dateString + "." + fileExtension;
        String addr = pathprefix+"/" + fileName;
        String rootFilePath = System.getProperty("user.dir") + "/"+resourcefile+"/"+fileName;
        FileUtil.writeBytes(file.getBytes(), rootFilePath);//使用Hutool工具包将我们接收到文件保存到rootFilePath中
        //返回文件路径
        //原始访问
//        return "https://" + IP + ":"+port+"/" + addr;
        //nginx代理api访问
        return IPAddress+ "/" + addr;
    }

}
